package com.danceforyou.common.controller;

import com.danceforyou.common.util.Constants;
import com.danceforyou.user.model.UserDO;
import com.danceforyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
@RequestMapping(value = "/")
public class AdminController {

    @Autowired(required = false)
    private HttpSession session;

    @RequestMapping(value = "/")
    public ModelAndView goAdminLogin(HttpServletResponse response) throws IOException {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        PrintWriter writer = response.getWriter();
        if (loginUser == null) {
            writer.write("<script language=JavaScript>" +
                    "	parent.parent.location.href='login.html';" +
                    "</script>");
        } else {
            writer.write("<script language=JavaScript>" +
                    "	parent.parent.location.href='index.html';" +
                    "</script>");
        }
        writer.flush();
        writer.close();
        return new ModelAndView("login");
    }

    @RequestMapping(value = "{url}.html")
    public ModelAndView interceptIllegalOperation(@PathVariable(value = "url") String url, HttpServletResponse response) throws IOException {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        if (loginUser == null && !url.equals("login")) {
            PrintWriter writer = response.getWriter();
            writer.write("<script language=JavaScript>" +
                    "	parent.parent.location.href='login.html';" +
                    "</script>");
            writer.flush();
            writer.close();
        }
        return new ModelAndView(url);
    }
}
